package cn.sc.summer.redis.redisson.strategy.impl;

import cn.sc.summer.redis.redisson.property.RedissonProperties;
import cn.sc.summer.redis.redisson.strategy.RedissonConfigService;
import cn.sc.summer.constant.redis.RedisConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.config.Config;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author a-xin
 * @Description: 主从部署Redisson配置
 * 连接方式:  主节点,子节点,子节点
 * 格式为:  127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381
 * @date 2019/6/19 下午9:21
 */

@Slf4j
@Service(value = "MasterSlaveConfigImpl")
public class MasterSlaveConfigImpl implements RedissonConfigService {

    @Override
    public Config createRedissonConfig(RedissonProperties redissonProperties) {
        Config config = new Config();
        try {
            String address = redissonProperties.getHost() + ":" + redissonProperties.getPort();
            String password = redissonProperties.getPassword();
            int database = redissonProperties.getDatabase();
            String[] addrTokens = address.split(",");
            String masterNodeAddr = addrTokens[0];
            //设置主节点ip
            config.useMasterSlaveServers().setMasterAddress(masterNodeAddr);
            if (StringUtils.isNotBlank(password)) {
                config.useMasterSlaveServers().setPassword(password);
            }
            config.useMasterSlaveServers().setDatabase(database);
            //设置从节点，移除第一个节点，默认第一个为主节点
            List<String> slaveList = new ArrayList<>();
            for (String addrToken : addrTokens) {
                slaveList.add(RedisConstant.REDIS_CONNECTION_PREFIX + addrToken);
            }
            slaveList.remove(0);

            config.useMasterSlaveServers().addSlaveAddress((String[]) slaveList.toArray());
            log.info("==> Initialize the [Master-Slave Deployment] mode Config, redisAddress:" + address);
        } catch (Exception e) {
            log.error("==> Master-slave deployment Redisson init error", e);
            e.printStackTrace();
        }
        return config;
    }

}
